import React, { Component } from 'react';
import {
	StyleSheet, Text, View, PixelRatio,
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import StorageHelper from '../../../utils/storageHelper'
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { HeaderSearch } from './_components/HeaderSearch';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ListComponent } from '../create/_components/ListComponent'
import { Common } from '../../../component/common/Common';
import HTTP from '../../../utils/http';

const scale = GLOBAL.SCALE;
const searchLeft = require('../../../imgs/customer/searchLeft.png');

const HISTORY = {
	L: 'FRAME_HISTORY',
	S: 'REPORT_HISTORY'
}

export class SeachPage extends Component {
	constructor(props) {
		super(props);
		this.sendData = { searchCode: '', periodType: props.navigation.state.params.periodType }
		this.historyKey = HISTORY[this.sendData.periodType];
		this.requesting = false;
		this.state = {
			orderList: [],
			loadIcon: false,  // 下拉涮新的 图标
			onOff: true,  // 控制搜索历史
			searchArr: [],
		}
		this.pageNo = 1;
		this.totalPage = 0;
		this.recordCount = 0;
		this.loadedNo = 0;
	}

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: (<HeaderSearch
				keyWord={params.searchCode}
				inputLeftIcon={searchLeft}
				onChangeText={(text) => { params.onChange(text); }}
				onSubmitEditing={() => { params.submitEdit() }}
			/>),
			headerTintColor: style.color.dark,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerRight: (
				<Text onPress={() => { params.doSearch() }} style={style.headTow.headerRight}>搜索</Text>
			),
			headerStyle: style.headTow.headerStyle,
			headerTitleStyle: style.headTow.headerTitleStyle,
		}
	}
	//搜索value
	onChange = (text) => {
		this.sendData.searchCode = text;
		this.refresh();
	}

	componentDidMount () {
		this.initSearch();
		this.getHistory();
	}

	initSearch = () => {
		this.props.navigation.setParams({
			submitEdit: this.refresh,
			onChange: this.onChange,
			doSearch: this.doSearch,
		});
	}

	//点击搜索词查询列表
	searchFind (value) {
		this.props.navigation.setParams({
			submitEdit: this.refresh,
			onChange: this.onChange,
			doSearch: this.doSearch,
			searchCode: value,
		});
		this.sendData.searchCode = value;
		this.refresh();
	}



	doSearch = () => {
		this.saveStorage(this.sendData.searchCode);
		this.refresh();
	}
	//获取数据
	async getData () {
		this.sendData.pageNo = this.pageNo;
		this.setState({
			loadIcon: true
		})
		this.requesting = true;
		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_LIST), this.sendData);
		this.requesting = false;
		this.setState({
			loadIcon: false
		});

		if (responseData) {
			this.totalPage = responseData.totalPage;
			this.recordCount = responseData.recordCount;
			let orderList = responseData.rows || [];
			if (this.pageNo > 1) orderList = [...this.state.orderList, ...orderList];
			this.loadedNo = orderList.length;
			this.setState({
				orderList,
				onOff: (orderList.length == 0)
			});
		}
	}

	//获取本地
	async getHistory () {
		var historyStr = await StorageHelper.get(this.historyKey);
		if (historyStr) {
			this.setState({
				searchArr: historyStr.split(',')
			});
		}
	}

	//保存搜索词
	async saveStorage (value) {
		if (!value) return;
		let { searchArr } = this.state;
		if (searchArr.indexOf(value) == -1) {
			searchArr.push(value);
			StorageHelper.set(this.historyKey, searchArr.toString());
			this.setState({ searchArr });
		}
	}

	// 下拉刷新
	refresh = () => {
		if (this.requesting) return;
		this.pageNo = 1;
		this.getData();
	}

	//上拉加载
	endReached = () => {
		if (this.requesting) return;
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this.getData();
		}
	}

	render () {
		let { orderList, loadIcon, onOff, searchArr } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.sendBox}>
					<View style={onOff ? null : styles.hidden}>
						<Text style={styles.title}>常用</Text>
						<View style={styles.sendItemBox}>
							{
								searchArr.map((value, index) => {
									return (
										<Text key={index} onPress={() => { this.searchFind(value) }} style={styles.sendItem} >{value}</Text>
									)
								})
							}
						</View>
					</View>
				</View>
				{orderList.length > 0 ? (
					<View style={{ flex: 1 }}>
						<Text style={styles.titleBox}>搜索结果</Text>
						{
							<ListComponent
								upLoad={this.refresh}
								downLoad={this.endReached}
								totalPage={this.totalPage}
								pageNo={this.pageNo}
								dataArray={orderList}
								loadIcon={loadIcon}
								recordCount={this.recordCount}
								nowList={this.loadedNo}
								navigate={this.props.navigation.navigate}
							/>
						}
					</View>
				) : (!onOff ? <PageStatusIndex status="empty" emptyText="没有搜到相关信息哦" /> : null)
				}
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white
	},
	sendBox: {
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
	},
	title: {
		fontSize: 14 * scale,
		color: style.color.dark,
		marginTop: 20 * scale
	},
	titleBox: {
		fontSize: 14 * scale,
		color: style.color.dark,
		marginTop: 20 * scale,
		marginBottom: 15 * scale,
		marginLeft: 15 * scale
	},
	sendItemBox: {
		flexDirection: 'row',
		flexWrap: 'wrap',
	},
	sendItem: {
		color: '#666',
		paddingLeft: 24 * scale,
		paddingRight: 24 * scale,
		height: 28 * scale,
		lineHeight: 28 * scale,
		backgroundColor: '#F8F8F8',
		marginTop: 12 * scale,
		marginRight: 10 * scale,
		borderRadius: 14 * scale
	},
	hidden: {
		height: 0,
		width: 0,
		overflow: 'hidden'
	}

})